App = {
    web3Provider: null,
    contracts: {},
    netaddr: 'http://127.0.0.1:8545',
    // netaddr: 'https://ropsten.infura.io/',

    init: function () {
        return App.initWeb3();
    },

    initWeb3: function () {
        // Initialize web3 and set the provider to the testRPC.
        if (typeof web3 !== 'undefined') {
            App.web3Provider = web3.currentProvider;
            web3 = new Web3(web3.currentProvider);
        } else {
            // set the provider you want from Web3.providers
            App.web3Provider = new Web3.providers.HttpProvider(App.netaddr);
            web3 = new Web3(App.web3Provider);
        }

        return App.initContract();
    },

    initContract: function () {
        $.getJSON('TutorialToken.json', function (data) {
            // Get the necessary contract artifact file and instantiate it with truffle-contract.
            let TutorialTokenArtifact = data;
            App.contracts.TutorialToken = TruffleContract(TutorialTokenArtifact);

            // Set the provider for our contract.
            App.contracts.TutorialToken.setProvider(App.web3Provider);

            // Use our contract to retieve and mark the adopted pets.
            // return App.getBalances();
            return App.getBalances();
        });
        return App.bindEvents();
    },

    bindEvents: function () {
        $(document).on('click', '#transferButton', App.handleTransfer);
    },

    handleTransfer: function (event) {
        event.preventDefault();

        let amount = parseFloat($('#TTTransferAmount').val());
        let toAddress = $('#TTTransferAddress').val();

        console.log('Transfer ' + amount + ' TT to ' + toAddress);

        web3.eth.getAccounts(function (error, accounts) {
            if (error) {
                console.log(error);
            }

            let tutorialTokenInstance;
            let account = accounts[0];

            App.contracts.TutorialToken.deployed().then(function (instance) {
                tutorialTokenInstance = instance;
                return tutorialTokenInstance.decimals();
            }).then(function(decimals) {
                return tutorialTokenInstance.transfer(toAddress, amount * Math.pow(10, decimals), {from: account});
            }).then(function(result) {
                alert('Transfer Successful!');
                return App.getBalances();
            }).catch(function(err) {
                console.error(err.message);
            });
        });
    },

    getBalances: function (adopters, account) {
        // console.log('Getting balances...');

        web3.eth.getAccounts(function (error, accounts) {
            if (error) {
                console.log(error);
            }

            let tutorialTokenInstance;
            let account = accounts[0], balance = 0, decimals = 0;

            App.contracts.TutorialToken.deployed().then(function (instance) {
                tutorialTokenInstance = instance;
                return tutorialTokenInstance.balanceOf(account)
            }).then(function (result) {
                balance = result;   // bignumber -> bignumber.js
                return tutorialTokenInstance.decimals();
            }).then(function (decimals) {
                let ttBalance = balance.div((Math.pow(10, 8))).toFixed(decimals);
                $('#TTBalance').text(ttBalance.toString());
            }).catch(function (err) {
                console.log(err.message);
            });
        });
    },
};

$(function () {
    $(window).load(function () {
        App.init();
    });
});
